package easytasks.ui;

import java.util.ArrayList;

import easytasks.data.DataManager;
import easytasks.data.DataSetup;
import easytasks.data.TaskCategory;
import easytasks.main.R;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TaskCategoryListActivity extends ListActivity 
{
	private AppMenu appMenu;
	
	private ArrayList<TaskCategory> categories = null;
	private DataSetup dataInit;
	private DataManager dataManager;
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.taskcategorylist);
        
        appMenu = new AppMenu(this);
        
        dataInit = new DataSetup(this);
        dataManager = new DataManager(dataInit, PreferenceManager.getDefaultSharedPreferences(this));
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	refresh();
    }
    
    private void refresh() 
    {
    	categories = new ArrayList<TaskCategory>(dataManager.getTaskCategories());
		ArrayList<String> menuItems = new ArrayList<String>(categories.size());
		
		for (TaskCategory category : categories)
		{	
			menuItems.add(category.getName() + " ("+ dataManager.getPendingTaskByCategoryCount(category) + ")");
		}
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menuItems);	
		setListAdapter(adapter);
		appMenu.refresh();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id)
	{
		Intent taskListIntent = new Intent(this, TaskListActivity.class);
		taskListIntent.putExtra("action", "by-category");
		taskListIntent.putExtra("category", categories.get(position));
		startActivity(taskListIntent);
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu)	
    {
    	super.onCreateOptionsMenu(menu);
    	return appMenu.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	return appMenu.onOptionsItemSelected(item);
    }
}
